package com.ruoyi.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.model.AppLoginUserV3;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.util.Date;

public class AppBaseV3Controller {

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 响应请求分页数据
     *
     * @param page
     * @return
     * @auther liuliya
     */
    protected TableDataInfo getDataTableByPage(IPage<?> page) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(page.getRecords());
        rspData.setTotal(page.getTotal());
        return rspData;
    }

    protected AppLoginUserV3 getAppLoginUser() {
        HttpServletRequest request = ServletUtils.getRequest();
        TokenService tokenService = SpringUtils.getBean(TokenService.class);
        AppLoginUserV3 appLoginUser = tokenService.getAppLoginUserV3(request);
        return appLoginUser;
    }

}
